﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using Common.Library;
using System.Threading.Tasks;

namespace Social_Celebrities
{
    public partial class FacebookLoginPage : PhoneApplicationPage
    {
        private const string AppId = "573753602688592";
      
        private const string ExtendedPermissions = "user_about_me,read_stream,publish_stream";

        private readonly FacebookClient _fb = new FacebookClient();

        public FacebookLoginPage()
        {
            InitializeComponent();
            Loaded += FacebookLoginPage_Loaded;
        }

        void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("AddAccount.xaml"))
                NavigationService.RemoveBackEntry();
        }

        private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
        {
            webBrowser1.ClearCookiesAsync();
            var loginUrl = GetFacebookLoginUrl(AppId, ExtendedPermissions);
            webBrowser1.Navigate(loginUrl);
        }

        //public static Task ClearCookiesAsync(this WebBrowser webbrowser1);

        private Uri GetFacebookLoginUrl(string appId, string extendedPermissions)
        {
            var parameters = new Dictionary<string, object>();
            parameters["client_id"] = appId;
            parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
            parameters["response_type"] = "token";
            parameters["display"] = "touch";
            if (!string.IsNullOrEmpty(extendedPermissions))
            {
                parameters["scope"] = extendedPermissions;
            }
            //_fb.GetLogoutUrl(parameters);
            return _fb.GetLoginUrl(parameters);
        }       

        private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult oauthResult;
            if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                return;
            }

            if (oauthResult.IsSuccess)
            {
                var accessToken = oauthResult.AccessToken;
                AppSettings.FaceBookAccessToken = accessToken;
                NavigationService.GoBack();
            }
            else
            {
                MessageBox.Show(oauthResult.ErrorDescription);
                NavigationService.GoBack();
            }            
        }         
    }
}